package com.dragon.aipictures.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.dragon.aipictures.Exception.StateCode;
import com.dragon.aipictures.util.ThrowUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

import static com.dragon.aipictures.constant.UrlConstant.ALLOW_CONTENT_TYPES;

@Component
public class FilePictureUpload extends PictureUploadTemplate{
    @Override
    public String validPicture(Object inputSource) {
        MultipartFile multipartFile=(MultipartFile)inputSource;
        ThrowUtil.throwIf(multipartFile==null, StateCode.PARAMS_ERROR,"文件不能为空");
//      校验文件大小
        long size = multipartFile.getSize();
        ThrowUtil.throwIf(size > 2 * ONE_M, StateCode.PARAMS_ERROR, "文件大小不能超过 2MB");
        // 2. 校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀列表（或者集合）
        ThrowUtil.throwIf(!ALLOW_CONTENT_TYPES.contains(fileSuffix), StateCode.PARAMS_ERROR, "不支持该文件类型");
        return fileSuffix;
    }

    @Override
    public String getOriginalFileName(Object inputSource) {
        MultipartFile multipartFile=(MultipartFile)inputSource;
        return multipartFile.getOriginalFilename();

    }

    @Override
    public void processFile(Object inputSource, File file) throws IOException {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);

    }
}
